package com.springboot.demo.threadpool;

import java.util.ArrayList;
import java.util.Set;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.Collectors;

public class CountingTask extends RecursiveTask<Integer>{
    public static void main(String[] args) {
        ForkJoinTest.TreeNode tree = new ForkJoinTest.TreeNode(5,
                new ForkJoinTest.TreeNode(3), new ForkJoinTest.TreeNode(2,
                new ForkJoinTest.TreeNode(2), new ForkJoinTest.TreeNode(8)));

        ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
        int sum = forkJoinPool.invoke(new CountingTask(tree));
        System.out.println(sum);

        ForkJoinPool forkJoinPool1 = ForkJoinPool.commonPool();
        String q = forkJoinPool1.invoke(new StringForkTest("qwertyuiopasdfghjklzxcvbnm"));
        System.out.println(q);

    }
    private final ForkJoinTest.TreeNode node;

    public CountingTask(ForkJoinTest.TreeNode node) {
        this.node = node;
    }

    @Override
    protected Integer compute() {
        return node.value + node.children.stream()
                .map(childNode -> new CountingTask(childNode).fork())
                .collect(Collectors.summingInt(ForkJoinTask::join));
    }
}
